import React, { useEffect, useRef, useState } from 'react';
import classNames from 'classnames';
import ResizeObserver from 'rc-resize-observer';

// 导入自定义 hooks
import useUpdateState from './hooks/useUpdateState';
import useOffsets from './hooks/useOffsets';
import useVisibleRange from './hooks/useVisibleRange';
import './index.less';
// 导入类型定义
import { OverflowTabsProps, TabItem, TabSizeMap } from './interface';

/**
 * OverflowTabs 组件
 * 一个处理标签页溢出的组件，当标签页太多无法全部显示时，
 * 会自动计算哪些标签页需要隐藏，并在"更多"下拉菜单中显示
 */
const OverflowTabs: React.FC<OverflowTabsProps> = ({
    tabs,
    activeKey,
    onChange,
    className,
    style,
}) => {
    // 引用和状态
    const containerRef = useRef<HTMLDivElement>(null);
    const tabListRef = useRef<HTMLDivElement>(null);
    const navWrapRef = useRef<HTMLDivElement>(null);
    const [containerWidth, setContainerWidth] = useState(0);
    const [scrollPosition, setScrollPosition] = useState(0);

    // 标签页尺寸信息
    const [tabSizes, setTabSizes] = useUpdateState<TabSizeMap>(new Map());

    // 计算偏移量
    const tabOffsets = useOffsets(tabs, tabSizes, containerWidth);

    // 计算可见范围
    const [visibleStart, visibleEnd] = useVisibleRange(
        tabOffsets,
        containerWidth,
        scrollPosition,
        tabs,
    );

    // 计算隐藏的标签页
    const startHiddenTabs = tabs.slice(0, visibleStart);
    const endHiddenTabs = tabs.slice(visibleEnd + 1);
    const hiddenTabs = [...startHiddenTabs, ...endHiddenTabs];
    const visibleTabs = tabs.slice(visibleStart, visibleEnd + 1);

    // 更新标签页尺寸信息
    const updateTabSizes = () => {
        setTabSizes(() => {
            const newSizes: TabSizeMap = new Map();
            const listRect = tabListRef.current?.getBoundingClientRect();

            if (!listRect) return newSizes;

            tabs.forEach(({ key }) => {
                const tabNode = tabListRef.current?.querySelector<HTMLElement>(
                    `[data-tab-key="${key}"]`,
                );

                if (tabNode) {
                    const { width, height } = tabNode.getBoundingClientRect();
                    const left = tabNode.offsetLeft;
                    const top = tabNode.offsetTop;

                    newSizes.set(key, { width, height, left, top });
                }
            });

            return newSizes;
        });
    };

    // 处理容器大小变化
    const handleResize = () => {
        if (containerRef.current) {
            setContainerWidth(containerRef.current.offsetWidth);
        }
        updateTabSizes();

        // 更新滚动位置
        if (navWrapRef.current) {
            setScrollPosition(navWrapRef.current.scrollLeft);
        }
    };

    // 监听滚动事件
    useEffect(() => {
        const navWrap = navWrapRef.current;
        // if (!navWrap) return;

        // const handleScroll = () => {
        //     setScrollPosition(navWrap.scrollLeft);
        // };

        // navWrap.addEventListener('scroll', handleScroll);
        // return () => {
        //     navWrap.removeEventListener('scroll', handleScroll);
        // };
    }, []);

    // 当 activeKey 变化时，滚动到激活的标签页
    useEffect(() => {
        if (activeKey) {
            // 通过 ID 获取 DOM 元素
            const tabElement = document.getElementById(
                `common-tab-${activeKey}`,
            );
            if (tabElement) {
                // 使用 scrollIntoView 方法滚动到元素
                tabElement.scrollIntoView({
                    behavior: 'smooth',
                    block: 'nearest',
                    inline: 'nearest',
                });
            }
            debugger;
            setScrollPosition(navWrapRef.current?.scrollLeft);
        }
    }, [activeKey]);

    // 初始化和更新
    useEffect(() => {
        updateTabSizes();
    }, [tabs]);

    return (
        <ResizeObserver onResize={handleResize}>
            <div
                className={classNames('overflow-tabs-container', className)}
                style={style}
                ref={containerRef}
            >
                <div className="overflow-tabs-nav">
                    <div
                        className="overflow-tabs-nav-wrap"
                        ref={navWrapRef}
                        // onScroll={() => {
                        //     if (navWrapRef.current) {
                        //         setScrollPosition(navWrapRef.current.scrollLeft);
                        //     }
                        // }}
                    >
                        <div
                            className="overflow-tabs-nav-list"
                            ref={tabListRef}
                        >
                            {tabs.map((tab) => (
                                <div
                                    key={tab.key}
                                    id={`common-tab-${tab.key}`}
                                    data-tab-key={tab.key}
                                    className={classNames('overflow-tabs-tab', {
                                        'overflow-tabs-tab-active':
                                            tab.key === activeKey,
                                        'overflow-tabs-tab-disabled':
                                            tab.disabled,
                                    })}
                                    onClick={() => {
                                        if (!tab.disabled && onChange) {
                                            onChange(tab.key);
                                        }
                                    }}
                                >
                                    {tab.label}
                                </div>
                            ))}
                        </div>
                    </div>

                    {hiddenTabs.length > 0 && (
                        <div className="overflow-tabs-more">
                            <button className="overflow-tabs-more-btn">
                                更多 ({hiddenTabs.length})
                            </button>
                            <div className="overflow-tabs-more-dropdown">
                                {hiddenTabs.map((tab) => (
                                    <div
                                        key={tab.key}
                                        id={`common-tab-dropdown-${tab.key}`}
                                        className={classNames(
                                            'overflow-tabs-more-item',
                                            {
                                                'overflow-tabs-more-item-active':
                                                    tab.key === activeKey,
                                                'overflow-tabs-more-item-disabled':
                                                    tab.disabled,
                                            },
                                        )}
                                        onClick={() => {
                                            if (!tab.disabled && onChange) {
                                                onChange(tab.key);
                                            }
                                        }}
                                    >
                                        {tab.label}
                                    </div>
                                ))}
                            </div>
                        </div>
                    )}
                </div>

                <div className="overflow-tabs-content">
                    {/* 这里可以放置标签页内容 */}
                </div>

                <div className="overflow-tabs-debug">
                    <div>
                        可见标签页: {visibleTabs.map((t) => t.key).join(', ')}
                    </div>
                    <div>
                        隐藏标签页: {hiddenTabs.map((t) => t.key).join(', ')}
                    </div>
                    <div>滚动位置: {scrollPosition}px</div>
                    <div>容器宽度: {containerWidth}px</div>
                </div>
            </div>
        </ResizeObserver>
    );
};

export default OverflowTabs;
